﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Presentation.Web.Admin.Controllers
{
    [HandleError]
    public class ProfileController : Infrastructure.Crosscutting.NetFramework.Controllers.BaseController
    {
        Infrastructure.Crosscutting.Authorize.IUserService userService;

        public ProfileController(Infrastructure.Crosscutting.NetFramework.IWorkContext work,
            Infrastructure.Crosscutting.Authorize.IUserService user)
            : base(work)
        {
            if (user == null)
            {
                throw new ArgumentNullException("userService is null");
            }
            userService = user;
        }

        public ViewResult Index()
        {
            Domain.Dto.UserDto data = null;
            if (this.WorkContext.CurrentUser != null)
            {
                data = this.WorkContext.CurrentUser.ToDto();
            }
            return View(data);
        }

        [HttpPost]
        public JsonResult Edit(Domain.Dto.UserDto dto)
        {
            var res = false;
            var message = "";
            if (dto.Id > 0 && !string.IsNullOrEmpty(dto.UserName))
            {
                var model = userService.GetUserModelById(dto.Id);
                model.UserName = dto.UserName;
                model.TrueName = dto.TrueName;
                model.Email = dto.Email;
                model.IsActivity = dto.IsActivity;
                model.Phone = dto.Phone;
                model.Sex = dto.Sex;
                model.SortNum = dto.SortNum;
                model.State = dto.State;
                if (!string.IsNullOrEmpty(dto.Pwd))
                {
                    model.Pwd = Infrastructure.Crosscutting.Comm.Service.StringService.Tomd5(dto.Pwd);
                }
                if (userService.Modify(model, this.WorkContext.CurrentUser))
                {
                    res = true;
                }
                else
                {
                    message = "修改失败了T_T";
                }
            }
            return Json(new { success = res, message = message }, JsonRequestBehavior.AllowGet);
        }
    }
}
